<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\model\wechat;

use app\common\model\AdminBaseModel;
use app\common\model\wechat\tralts\WechatModel;
use hiduoke\services\WechatService;

class WechatShare extends AdminBaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'wechat_share';

    /**
     * 字段类型或者格式转换
     * @var array
     */
    protected $type = [
        'receivers' => 'json'
    ];

    public $append = [
        'wechat_order',
        'receivers_count',
        'amount_count',
        'state_text'
    ];

    public $states = [
        -1 => "分账失败",
        0  => "未分账",
        1  => "已分账"
    ];

    use WechatModel;

    /**
     * @var WechatShareReceiver
     */
    public WechatShareReceiver $Receiver;

    public function __construct(array $data = [])
    {
        parent::__construct($data);
        $this->Receiver = new WechatShareReceiver();
    }

    public function wechatOrder()
    {
        return $this->belongsTo(WechatOrder::class, 'transaction_id', 'transaction_id');
    }

    public function Receiver()
    {
        return $this->belongsToMany(WechatShareReceiver::class, 'transaction_id', 'transaction_id');
    }

    public function getStateTextAttr($val, $data)
    {
        return $this->states[$data['state']];
    }

    public function getExecTimeTextAttr($val, $data)
    {
        return date("Y-m-d H:i:s", $data['exec_time']);
    }

    //处理分账订单
    public static function handleShareTask()
    {
        $wechatServices = [];
        //获取任务
        $shares = self::where('err_count', '<=', 2)
            ->where('status', '<>', 'FINISHED')
            ->where('exec_time', '<', time())
            ->select();
        if (count($shares) > 0) {
            //大于0执行
            foreach ($shares as $key => $share) {
                $plaid = $share['plaid'];//平台ID
                if (!isset($wechatServices[$plaid])) {
                    $wechatServices[$plaid] = new WechatService($plaid);
                }
                $Ws = $wechatServices[$plaid];
                $receivers = $share['receivers'];
                if ($receivers && count($receivers) > 0) {
                    $Ws->share($share['transaction_id'], $receivers, $share['out_order_no']);
                }
            }
        }
    }
}
